﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UpdateApp
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        //https://fanyi-api.baidu.com/api/trans/product/desktop
        //标准版：
        //完全免费，不限使用字符量（QPS=1）；
        //高级版：
        //每月前200万字符免费，超出后仅收取超出部分费用（QPS=10），49元/百万字符；

        string BaiduAppID = System.Configuration.ConfigurationManager.AppSettings["BaiduAppID"];
        string BaiduSecretKey = System.Configuration.ConfigurationManager.AppSettings["BaiduSecretKey"];

        protected void Page_Load(object sender, EventArgs e)
        {
            string word = Request["word"];

            if (string.IsNullOrEmpty(word))
            {
                Response.Write("");

                Response.End();
            }

            string row = Convert(word);

            Response.Write(row);
            Response.End();
        }

        private string Convert(string word)
        {
            List<string> arr = word.Split('=').ToList();

            var json = FileHelper.GetAppData("Translate");

            var dic = json != null ? JsonConvert.DeserializeObject<Dictionary<string, string>>(json) : new Dictionary<string, string>();

            string flag = "";
            foreach (var item in dic.Keys)
            {
                if (arr[0].IndexOf(item) == 0)
                {
                    arr[0] = dic[item];
                    arr.Add(item);

                    return string.Join("=", arr);
                }
                else if (arr[0].IndexOf(item) > 0)
                {
                    arr[0] = arr[0].Replace(item, "") + dic[item];
                    flag = item;

                    break;
                }
            }

            string temp = arr[0];

            TransApi transApi = new TransApi(BaiduAppID, BaiduSecretKey);
            string result = transApi.GetTransResult(temp, "auto", "auto").Trim();

            //当为中文时去除包含的英文
            if (Regex.IsMatch(temp.Substring(0, 1), "^[\u4e00-\u9fa5]{0,}$"))
            {
                temp = Regex.Replace(temp, "[a-z]", "", RegexOptions.IgnoreCase);

                arr[0] = result;
                arr.Add(temp + flag);
            }
            //当为英文时，将英文置前，中文置后
            else
            {
                arr[0] = temp;
                arr.Add((result));
            }

            return string.Join("=", arr);
        }
    }
}